package com.lw.lost.adapters

import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.lw.lost.R
import com.lw.lost.activity.UserDetailActivity
import com.lw.lost.databinding.ItemUserBinding
import com.lw.lost.models.User

class UserAdapter : ListAdapter<User, UserAdapter.ViewHolder>(DiffCallback()) {
    
    inner class ViewHolder(private val binding: ItemUserBinding) : RecyclerView.ViewHolder(binding.root) {
        fun bind(user: User) {
            binding.apply {
                tvName.text = user.name
                tvInfo.text = "年龄：${user.age}  性别：${if (user.gender == 0) "男" else "女"}"

                // 加载圆形头像
                Glide.with(ivAvatar)
                    .load(user.avatar)
                    .circleCrop()
                    .placeholder(R.drawable.ic_avatar_default)
                    .error(R.drawable.ic_avatar_default)
                    .into(ivAvatar)

                // 显示未读消息数
                if (user.unreadCount > 0) {
                    tvUnreadCount.visibility = View.VISIBLE
                    tvUnreadCount.text = if (user.unreadCount > 99) "99+" else user.unreadCount.toString()
                } else {
                    tvUnreadCount.visibility = View.GONE
                }

                // 添加点击事件
                root.setOnClickListener {
                    val intent = Intent(root.context, UserDetailActivity::class.java)
                    intent.putExtra("userId", user.userId)
                    root.context.startActivity(intent)
                }
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(
            ItemUserBinding.inflate(
                LayoutInflater.from(parent.context),
                parent,
                false
            )
        )
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(getItem(position))
    }

    private class DiffCallback : DiffUtil.ItemCallback<User>() {
        override fun areItemsTheSame(oldItem: User, newItem: User): Boolean {
            return oldItem.userId == newItem.userId
        }

        override fun areContentsTheSame(oldItem: User, newItem: User): Boolean {
            return oldItem == newItem
        }
    }
} 